package com.why.client;

import com.why.message.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: why-rpc-framework
 * @description:
 * @author: @why
 * @create: 2021-03-15 17:19
 **/
@Slf4j
public class ProxyClient  implements InvocationHandler {
    private RpcClient client;
    public ProxyClient(RpcClient client){
        this.client=client;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //先封装好请求
        RpcRequest request = RpcRequest.builder()
                .methodName(method.getName())
                .interfaceName(method.getDeclaringClass().getCanonicalName())
                .methodParameters(args)
                .parameterTypes(method.getParameterTypes()).build();


      log.info("请求创建完成{}",request);

      //接着在代理类中发送请求即可.
    Object object= client.sendRequest(request);
    log.info("调用请求成功!!!调用后得到的请求信息为{}",object);
    return  object;

    }

    public Object getProxy(Class<?> service){
        return Proxy.newProxyInstance(service.getClassLoader(),new Class<?>[]{service},this);
    }
}
